package xin.nick.roc.consumer.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import xin.nick.roc.consumer.handler.RpcClientHandler;

import java.util.Objects;
import java.util.concurrent.*;
import java.util.logging.Logger;

/**
 * @author Nick
 * @date 2021/7/4
 * @description rpc客户端
 */
@Slf4j
public class RpcClient {

    private EventLoopGroup group;

    private Channel channel;

    private String ip;

    private int port;

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();

    private ExecutorService executorService = new ScheduledThreadPoolExecutor(2,
            new DefaultThreadFactory("client-pool"));

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }

    public void initClient() {
        try {
            // 创建线程组
            group = new NioEventLoopGroup();

            // 创建启动线程助手
            Bootstrap bootstrap = new Bootstrap();

            // 设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            // 添加String编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());

                            // 添加客户端处理请求
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            channel = bootstrap.connect(ip, port).sync().channel();
            log.info("已初始化: {}", toString());
        } catch (Exception e) {
            e.printStackTrace();
            close();
        }
    }


    public void close() {
        try {
            if (Objects.nonNull(channel)) {
                channel.close();
            }
            if (Objects.nonNull(group)) {
                group.shutdownGracefully();
            }
        } catch (Exception e) {
            log.error("close channel fail", e);
        }
    }

    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMsg(msg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    @Override
    public String toString() {
        return "RpcClient{" +
                "group=" + group +
                ", channel=" + channel +
                ", ip='" + ip + '\'' +
                ", port=" + port +
                ", rpcClientHandler=" + rpcClientHandler +
                ", executorService=" + executorService +
                '}';
    }
}
